home *** CD-ROM | disk | FTP | other *** search
/ C# & Game Programming - A…er's Guide (2nd Edition) / Buono 2nd Ed.iso / GameClasses / Utils.cs < prev    next >
Encoding:
Text File  |  2004-09-07  |  2.4 KB  |  66 lines

  1. /* Utils.cs - Contains the Utils class which has a collection of 
  2.  * functions that can simplify development elsewhere.
  3.  *
  4.  * See individual function comments for more details.
  5.  */
  6.  
  7. using System;
  8. using System.Drawing;
  9. using System.IO;
  10. using System.Windows.Forms;
  11. using System.Runtime.InteropServices;
  12. using System.Threading;
  13.  
  14. namespace GameClasses {
  15.     public class Utils {
  16.         // External function to play sounds
  17.         [DllImport("winmm.dll")]
  18.         public static extern long PlaySound(String lpszName, long hModule, 
  19.             long dwFlags);
  20.  
  21.         // Static Variable .config file's contents
  22.         public static System.Collections.Specialized.NameValueCollection 
  23.             Config = System.Configuration.ConfigurationSettings.AppSettings;
  24.  
  25.         // Error-handling LoadImage function
  26.         public static Image LoadImage(String strFileName) {
  27.             Image imgLoad = null;
  28.             try {
  29.                 imgLoad = Image.FromFile(strFileName);
  30.             } catch (FileNotFoundException ex) {
  31.                 MessageBox.Show("Please check that the following file " +
  32.                     "exists:\n\n" + ex.Message + "\n\nCorrect the file " +
  33.                     "referenced in the config file.", "File Not Found!");
  34.                 Application.Exit();
  35.             }
  36.  
  37.             return imgLoad;
  38.         }
  39.  
  40.         // PlaySound simple pass-through function. Removes dependency for
  41.         // other classes to reference winmm.DLL.
  42.         public static void PlaySound(String strFileName) {
  43.             ThreadedSound snd = new ThreadedSound(strFileName);
  44.             Thread worker = new Thread(new ThreadStart(snd.Play));
  45.             worker.Start();
  46.         }
  47.  
  48.         /* While this thread does speed up the games, it also causes a very 
  49.         unnatural delay - note how the sounds continue to play after the game is shutdown.
  50.         The solution, simply replace the calls to this funciton with the sound functions 
  51.         used with DirectSound. DirectSound is covered in chapter six. */
  52.         class ThreadedSound {
  53.             public string strFileName;
  54.  
  55.             public ThreadedSound(string file) {
  56.                 strFileName = file;
  57.             }
  58.  
  59.             public void Play() {
  60.                 //Console.WriteLine("Playing: " + strFileName);
  61.                 PlaySound(strFileName, 0, 0);
  62.             }
  63.         }
  64.     }
  65. }
  66.